策略模式定义了算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户
类图
示例
定义策略接口
public interface Strategy {
void doSomething();
}
多种策略实现:
public class ConcreteStrategyA implements Strategy {
@overrite
void doSomething(){
}
}
public class ConcreteStrategyB implements Strategy {
@overrite
void doSomething(){
}
}
策略管理类:
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
void doSomething(){
this.strategy.doSomething();
}
}
使用:
// 使用策略A
Context context = new Context(new ConcreteStrategyA());
context.doSomething();
// 使用策略B
Context context = new Context(new ConcreteStrategyB());
context.doSomething();